<template>
  <div>
    <a-modal :visible="visible" :title="modalTitle" width="90%" @cancel="handleClose" :footer="null" class="tomb-modal">
      <div class="container">
        <div class="main">
          <div class="panel">
            <aside class="sidebar">
              <div class="sidebar-header">
                <span>墓地区域</span>
                <a-icon type="reload" @click="handleTreeRefresh" />
              </div>
              <a-tree ref="treeRef" v-if="treeData.length" show-line show-icon :tree-data="treeData" :expanded-keys="expandedKeys" :selected-keys="selectedKeys" @select="handleOnTreeSelect" @expand="handleOnTreeExpand" />
            </aside>
            <main class="content">
              <section class="stats-section">
                <template>
                  <div class="section-content">
                    <div class="section-left">
                      <div class="title-area">
                        <div class="title-left">
                          <h2 class="stats-title">{{ selectedTreeTitles }}</h2>
                        </div>
                        <div class="search-inputs">
                          <a-input-search v-model="searchForm['szxx.szxm']" placeholder="逝者姓名" allowClear />
                          <a-input-search v-model="searchForm.xm" placeholder="家属姓名" allowClear />
                          <a-select :style="mwztSelectStyle" v-model="searchForm.mwzt" placeholder="墓位状态" allowClear mode="multiple">
                            <a-select-option v-for="(item, index) in tombLocationStatus" :key="index" :value="item.value">{{ item.text }}</a-select-option>
                          </a-select>
                          <a-select style="width: 100px" v-model="searchForm.mx" placeholder="墓型" allowClear>
                            <a-select-option v-for="(item, index) in TombTypeLegends" :key="index" :value="item.path">{{ item.text }}</a-select-option>
                          </a-select>
                          <!-- <a-popover title="Title">
                            <template slot="content">
                            </template>
                            <a-button type="primary" icon="download">筛选</a-button>
                          </a-popover> -->
                          <a-button type="primary" icon="search" @click="handleSearch">搜索</a-button>
                          <a-button icon="redo" @click="handleResetSearch">重置</a-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </section>
              <section class="list-section" :class="{ 'is-empty': !resultTreeData.length }">
                <template v-if="resultTreeData.length">
                  <DynamicScroller class="scroller" :items="flattenedTombData" :min-item-size="200" key-field="id">
                    <template v-slot="{ item, index, active }">
                      <DynamicScrollerItem :item="item" :active="active" :data-index="index" :size-dependencies="[item.children?.length, item.title]" :min-size="200">
                        <div class="list-row">
                          <div class="row-header">
                            {{ formatRowNumber(item.title) }}
                          </div>
                          <div class="tomb-grid">
                            <!-- 原有的墓位内容 -->
                            <div v-for="(citem, cindex) in item.children" :key="cindex" class="item-box" :class="{ 'selected-item-tomb': selectedItems.includes(citem) }" @click="handleItemClick(citem)">
                              <!-- 原有的墓位内容保持不变 -->
                              <div class="tombstone-title">
                                <div>{{ citem.data.data.mwh }}</div>
                                <div :style="{ color: citem.data.bg }">
                                  {{ citem.data.data.mwzt }}
                                </div>
                              </div>
                              <!-- 添加逝者姓名显示 -->
                              <div class="deceased-name">
                                <template v-if="citem.data.data.szxx && citem.data.data.szxx.length">
                                  <a-tooltip placement="top">
                                    <template slot="title">
                                      <div>逝者: {{ formatDeceasedNames(citem.data.data.szxx, false) }}</div>
                                      <div v-if="citem.data.data.xm">家属: {{ citem.data.data.xm }}</div>
                                    </template>
                                    <span class="name-text">
                                      <span v-if="citem.data.data.szxx.length">
                                        <a-icon type="team" />
                                        {{ formatDeceasedNames(citem.data.data.szxx, true) }}
                                      </span>
                                      <span v-if="citem.data.data.xm" class="relative-name">
                                        <a-icon type="user" />
                                        {{ citem.data.data.xm }}
                                      </span>
                                    </span>
                                  </a-tooltip>
                                </template>
                                <template v-else>
                                  <span class="name-text">
                                    <a-icon type="team" />
                                    暂无逝者信息
                                  </span>
                                </template>
                              </div>
                              <div :class="getTombstoneComponent(citem.data.data.mx)">
                                <div class="tombstone-box" v-for="(mitem, mindex) in setCounts(citem.data.data)" :key="mindex">
                                  <div class="tombstone-circle" :style="{ background: mitem.bg }"></div>
                                  <div class="tombstone-rectangle" :style="{ background: mitem.bg }"></div>
                                  <div class="tombstone-bottom-rectangle" :style="{ background: mitem.bg }"></div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="row-divider" v-if="index < flattenedTombData.length - 1"></div>
                      </DynamicScrollerItem>
                    </template>
                  </DynamicScroller>
                </template>
                <a-empty content="暂无数据" style="margin-top: 60px" v-else-if="isEmptyBoxVisible && !legendInfoBoxVisible" />
                <div class="legend-info" v-if="legendInfoBoxVisible">
                  <a-row :gutter="10">
                    <a-col :span="8">
                      <a-card title="墓型图例">
                        <div class="tomb-type-legend">
                          <div class="tomb-status-item" v-for="(item, index) in TombTypeLegends" :key="index">
                            <div class="tomb-type-color">
                              <img v-if="item.path == 'dxmx'" style="width: 100%; height: 100%" src="../../static/dx.jpg" />
                              <img v-if="item.path == 'sxmx'" style="width: 100%; height: 100%" src="../../static/sx.jpg" />
                              <img v-if="item.path == 'duoxmx'" style="width: 100%; height: 100%" src="../../static/dg.jpg" />
                            </div>
                            <div>{{ item.text }}</div>
                          </div>
                        </div>
                      </a-card>
                    </a-col>
                    <a-col :span="8">
                      <a-card title="墓穴状态颜色图例">
                        <div class="tomb-status-legend">
                          <div class="tomb-status-item" v-for="(item, index) in legendTombLocationStatus" :key="index">
                            <template v-if="item.group && Array.isArray(item.group)">
                              <div class="tomb-status-color" :style="{ background: item.color }"></div>
                              <div>{{ item.text }}</div>
                              <!-- 显示带有子项的组 -->
                              <div class="tomb-status-group">
                                <div v-for="(subItem, subIndex) in item.group" :key="subIndex" class="tomb-status-sub-item">
                                  <div class="tomb-status-color" :style="{ background: subItem.color }"></div>
                                  <div>{{ subItem.text }}</div>
                                </div>
                              </div>
                            </template>
                            <template v-else>
                              <!-- 显示普通项 -->
                              <div class="tomb-status-color" :style="{ background: item.color }"></div>
                              <div>{{ item.text }}</div>
                            </template>
                          </div>
                        </div>
                      </a-card>
                    </a-col>
                    <a-col :span="8">
                      <a-card title="部分墓穴安葬图例">
                        <div class="tomb-type-legend">
                          <div class="tomb-status-item" v-for="(item, index) in TombTypePartLegends" :key="index">
                            <div class="tomb-type-color">
                              <img v-if="item.path === 1" style="width: 100%; height: 100%" src="../../static/bf3.jpg" />
                              <img v-if="item.path === 2" style="width: 100%; height: 100%" src="../../static/bf2.png" />
                              <img v-if="item.path === 3" style="width: 100%; height: 100%" src="../../static/bf1.png" />
                            </div>
                            <div>{{ item.text }}</div>
                          </div>
                        </div>
                      </a-card>
                    </a-col>
                  </a-row>
                </div>
              </section>
            </main>
          </div>
        </div>
        <div class="loading-mask" v-if="spinning">
          <a-spin :spinning="spinning" tip="加载中..." size="large" />
        </div>
      </div>
    </a-modal>

    <!-- 修改详情弹窗 -->
    <a-modal :title="detailModalTitle" :visible="detailVisible" cancelText="关闭" okText="确定" width="850px" :bodyStyle="{ height: '600px', overflow: 'auto', padding: '16px' }" @cancel="handleDetailCancel" @ok="handleDetailConfirm" class="tomb-detail-dialog">
      <div class="tomb-detail-wrapper">
        <!-- 墓位基本信息 -->
        <div class="detail-section">
          <div class="section-header">
            <span class="header-icon">
              <a-icon type="environment" style="color: #1890ff" />
            </span>
            <span class="header-title">墓位信息</span>
          </div>
          <a-descriptions bordered>
            <a-descriptions-item label="墓位地址" :span="2">
              {{ detailModalTitle }}
            </a-descriptions-item>
            <a-descriptions-item label="墓位状态">
              <a-badge :status="modalItem.data?.mwzt == '已销售' ? 'success' : 'processing'" :text="modalItem.data?.mwzt" />
            </a-descriptions-item>
            <a-descriptions-item label="墓型">
              {{ modalItem.data?.mx }}
            </a-descriptions-item>
            <a-descriptions-item label="墓位价格">
              <span class="price-text">{{ modalItem.data?.mwjg }}元</span>
            </a-descriptions-item>
            <a-descriptions-item label="管理费">
              <span class="price-text">{{ modalItem.data?.glf }}元</span>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 逝者信息 -->
        <template v-if="modalItem.data?.szxx?.length">
          <div class="detail-section">
            <div class="section-header">
              <span class="header-icon">
                <a-icon type="environment" style="color: #1890ff" />
              </span>
              <span class="header-title">逝者信息</span>
            </div>
            <div class="deceased-grid">
              <div v-for="(sz, index) in modalItem.data.szxx" :key="index" class="deceased-card">
                <div class="card-header">
                  <span class="card-title">逝者 {{ index + 1 }}</span>
                  <span class="card-name">{{ sz.szxm }}</span>
                </div>
                <div class="card-content">
                  <div class="info-row">
                    <span class="label">性别:</span>
                    <span>{{ sz.xb }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">民族:</span>
                    <span>{{ sz.mz }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">身份证号:</span>
                    <span>{{ sz.sfzh }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">籍贯:</span>
                    <span>{{ sz.jg }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">出生日期:</span>
                    <span>{{ sz.csrq }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">逝世日期:</span>
                    <span>{{ sz.sssj }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">与持证人关系:</span>
                    <span>{{ sz.qrsczrd }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 家属信息 -->
        <div v-if="modalItem.data?.xm" class="detail-section">
          <div class="section-header">
            <span class="header-icon">
              <a-icon type="user" style="color: #1890ff" />
            </span>
            <span class="header-title">家属信息</span>
          </div>
          <div class="relative-card">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">姓名:</span>
                <span>{{ modalItem.data.xm }}</span>
              </div>
              <div class="info-item">
                <span class="label">联系电话:</span>
                <span>{{ modalItem.data.lxdh }}</span>
              </div>
              <div class="info-item full-width">
                <span class="label">身份证号:</span>
                <span>{{ modalItem.data.sfzh }}</span>
              </div>
              <div class="info-item full-width">
                <span class="label">联系地址:</span>
                <span>{{ modalItem.data.lxdz }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Modal, Tree, Collapse, Dropdown, Spin, Descriptions, Table, Tooltip, Form, TreeSelect, FormModel, Card, Row, Col } from '@h3/antd-vue';
import Api from '../../apis/ofy';
import { val } from 'cheerio/lib/api/attributes';
import { DynamicScroller, DynamicScrollerItem } from 'vue-virtual-scroller';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css';

interface ReturnResult {
  data: any;
  errcode: number;
  errmsg: string;
  traceId: string;
}

@Component({
  name: 'KshModal',
  components: {
    ATree: Tree,
    ACollapse: Collapse,
    ACollapsePanel: Collapse.Panel,
    ADropdown: Dropdown,
    ASpin: Spin,
    Amodal: Modal,
    ADescriptions: Descriptions,
    ATable: Table,
    ATooltip: Tooltip,
    AForm: Form,
    AFormItem: Form.Item,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    ACard: Card,
    ARow: Row,
    ACol: Col,
    DynamicScroller,
    DynamicScrollerItem,
  },
})
export default class KshModal extends Vue {
  @Prop({ type: Boolean, default: false }) visible!: boolean;
  @Prop({ type: Boolean, default: false }) multiple!: boolean;
  @Prop({ type: Function }) onSelect?: (selectedItems: any[]) => void;
  @Prop({ type: [Object, String], default: () => ({}) }) filterConfig!: Record<string, any> | string;

  // 添加一个内部的配置数据
  private internalFilterConfig: Record<string, any> = {};

  // 添加标题属性
  modalTitle: string = '墓位查询'; // 默认标题

  // 回调函数属性
  onClose: Function | null = null;
  onConfirm: Function | null = null;
  onSelect: Function | null = null;
  callbackConfig: any[] = [];

  // 树形结构请求参数
  treeParams: any = {
    filters: [],
    mobile: false,
    page: 0,
    queryCode: 'mwsxsjb',
    schemaCode: 'mwsxsjb',
    size: 10000,
    queryVersion: 1,
    queryCondition: [[]],
    view: {
      type: 'TREE',
      depth: 1,
      parentRef: '#',
    },
    showTotal: false,
  };

  // 列表请求参数
  queryParams: any = {
    filters: [],
    mobile: false,
    page: 0,
    queryCode: 'mwkc',
    schemaCode: 'mwkc',
    size: 50000,
    queryVersion: 1,
    queryCondition: [],
    showTotal: false,
  };

  // 详情请求参数
  detailParams: any = {
    sheetCode: 'mwkc',
    objectId: '',
    schemaCode: 'mwkc',
    isWorkFlow: false,
    _viewCode: 'mwkc',
    return: Date.now(),
    relevanceInfo: { _viewCode: 'mwkc' },
    isMobile: false,
  };

  // 加载态
  spinning: Boolean = false;

  phSpinning: Boolean = false;

  checkedStrategy: any = (TreeSelect as any).SHOW_ALL;
  // 编辑价格表单
  editPriceForm: any = {
    all: undefined,
    mwjg: '',
    glf: '',
    mwy: '',
    mwq: '',
    mwp: '',
    mwh: '',
    mwzt: undefined,
  };

  // 编辑价格表单验证规则
  editPriceRules: any = {
    all: [{ required: true, message: '请选择墓地址' }],
  };

  // 树形结
  treeData: any[] = [];

  // 复制树形结构
  copyTreeData: any[] = [];

  // 结果树形结构
  resultTreeData: any[] = [];

  // 激活的键值
  activeKey: any[] = [];

  phTreeData: any[] = [];

  // 展开的键值
  expandedKeys: string[] = [];

  // 选中的键值
  selectedKeys: string[] = [];

  // 树节点选择
  selectedTreeMwyItem: string = '';
  selectedTreeMwqItem: string = '';
  selectedTreeMwpItem: string = '';
  selectedTreeTitles: string = '';
  selectedGraveStatus: string = '';
  selectedShapeStatus: string = '';
  selectedTreeDateRef: any = null;
  legendInfoBoxVisible: Boolean = false;

  isEmptyBoxVisible: Boolean = false;

  // 墓位状态
  tombLocationStatus: any = [
    // { text: '待售', value: 'ds', color: '#32CD32' }, // LimeGreen
    // { text: '已预留', value: 'yyl', color: '#FF1493' }, // Orange
    // { text: '已预订', value: 'yyd', color: '#FF6347' }, // Tomato
    // { text: '已销售', value: 'yxs', color: '#4682B4' }, // SteelBlue
    // { text: '已安葬', value: 'yaz', color: '#708090' }, // SlateGray
    // { text: '已迁出', value: 'yqc', color: '#DC143C' }, // Crimson
    // { text: '二次预留', value: 'ecyl', color: '#8A2BE2' }, // Yellow
    // { text: '二次预订', value: 'ecyd', color: '#FF8C00' }, // DarkOrange
    // { text: '二次销售', value: 'ecxs', color: '#20B2AA' }, // LightSeaGreen
    // { text: '二次销售安葬', value: 'ecxsaz', color: '#8B0000' }, // Orange
  ];

  legendTombLocationStatus: any = [
    { text: '待售', value: 'ds', color: '#32CD32' }, // LimeGreen
    { text: '未开放', value: 'wkf', color: '#DDA0DD' }, // LimeGreen
    { text: '已预留', value: 'yyl', color: '#FF1493' }, // Gold
    { text: '已预订', value: 'yyd', color: '#FF6347' }, // Tomato
    {
      text: '已销售',
      value: 'yxs',
      color: '#4682B4',
      group: [
        {
          text: '未存逝者',
          value: 'yxs',
          color: '#4682B4',
        },
        {
          text: '已存逝者',
          value: 'yxsaz',
          color: '#2F4F4F',
        },
      ],
    }, // SteelBlue
    {
      text: '已安葬',
      value: 'yaz',
      color: '#708090',
      group: [
        {
          text: '未下葬',
          value: 'yaz',
          color: '#708090',
        },
        {
          text: '已下葬',
          value: 'yaz',
          color: '#000000',
        },
      ],
    },
    { text: '已迁出', value: 'yqc', color: '#DC143C' }, // Crimson
    { text: '二次预留', value: 'ecyl', color: '#8A2BE2' }, // Yellow
    { text: '二次预订', value: 'ecyd', color: '#FF8C00' }, // DarkOrange
    { text: '二次销售', value: 'ecxs', color: '#20B2AA' }, // LightSeaGreen
    { text: '二次销售安葬', value: 'ecxsaz', color: '#8B0000' }, // Orange
  ];

  // 墓型部分状态
  TombTypeLegends: any[] = [
    { path: 'dxmx', text: '单穴墓型' },
    { path: 'sxmx', text: '双穴墓型' },
    { path: 'duoxmx', text: '多穴墓型' },
  ];

  // 墓型部分状态
  TombTypePartLegends: any[] = [
    { path: 1, text: '部分已销售' },
    { path: 2, text: '部分双穴已安' },
    { path: 3, text: '部分多穴已预定' },
  ];

  // 搜索表单
  searchForm = {
    'szxx.szxm': '', // 逝者姓名
    xm: '', // 家属姓名
    // mwh: '', // 墓穴号
    mx: undefined, // 墓型
    mwzt: undefined, // 墓穴状态
  };

  // 统计数据
  stats = {
    total: 0,
    reserved: 0,
    retained: 0,
    sold: 0,
    moved: 0,
    remaining: 0,
  };

  hasMoreConditions = true; // 控制是否显示更多条件按钮

  isCollapsed: Boolean = false;

  isStatsCollapsed: Boolean = false;

  // 添加详情弹窗控制
  detailVisible: boolean = false;
  detailModalTitle: string = '';
  modalItem: any = {};

  // 添加新的数据属性
  selectedItems: any[] = []; // 存储选中的项
  showBasicInfo: boolean = false; // 控制基础信息显示

  // 对照信息
  compareInfo: any[] = [];
  compareParams: any = {
    filters: [],
    mobile: false,
    page: 0,
    queryCode: 'gsbm',
    schemaCode: 'gsbm',
    size: 20,
    queryVersion: 1,
    queryCondition: [],
    showTotal: false,
  };

  handleTreeRefresh() {
    this.selectedTreeMwyItem = '';
    this.selectedTreeMwqItem = '';
    this.selectedTreeMwpItem = '';
    this.selectedTreeTitles = '';
    this.treeParams.view.parentRef = '#';
    this.treeData = [];
    this.copyTreeData = [];
    this.selectedKeys = [];
    this.expandedKeys = [];
    this.legendInfoBoxVisible = true;
    this.resultTreeData = [];
    this.getTreeList();
  }

  get userInfo() {
    return JSON.parse(window.sessionStorage.getItem('user') || '{}');
  }

  getCompareInfoPropertyValue(item) {
    console.log('🚀 ~ getCompareInfoPropertyValue ~ item:', item);
    const result = item.map((i) => {
      return {
        id: i.data.gs[0].id,
        name: i.data.gs[0].name,
        unitType: 1,
      };
    });
    return JSON.stringify(result);
  }

  getCompareInfo() {
    let currentUser = this.userInfo;
    if (!currentUser) return;
    this.compareParams.queryCondition = [
      [
        [
          {
            queryFilterType: 'Eq',
            propertyCode: 'bm',
            propertyType: 60,
            propertyValue: `[{"id":"${currentUser.currentDeptId}","unitType":1,"name":"${currentUser.currentDeptName}"}]`,
          },
        ],
      ],
    ];
    Api.getList(this.compareParams).then((result) => {
      if (result.errcode == 0) {
        this.compareInfo = result.data.content;
        console.log('🚀 ~ getCompareInfo ~ result:', result);
      }
    });
  }

  /**
   * 获取列表数据
   * 调用Api.getList接口，传入当前组件的参数来获取列表数据
   * 此函数说明了组件如何从后端获取数以展示列表
   */
  getTreeList() {
    this.spinning = true;
    Api.getList(this.treeParams).then(async (result) => {
      this.spinning = false;
      if (result.errcode == 0 && result.data.content.length) {
        this.treeData = this.constructTreeData(result.data.content);
        this.copyTreeData = this.constructTreeData(result.data.content, false);

        console.log('this.treeData', this.treeData);

        if (this.treeData.length && this.treeData[0].key) {
          let config = null;
          // 如果有配置数据,优先使用配置
          if (this.callbackConfig?.length) {
            console.log('🚀 ~ getTreeList ~ this.callbackConfig:', this.callbackConfig);
            config = await this.handleConfigData(this.callbackConfig);
          }

          console.log('🚀 ~ getTreeList ~ config:', config);

          const useConfigData = (data) => {
            // 使用展开的节点键值数组
            this.expandedKeys = data.expandedKeys || [data.expandedKey];
            this.selectedKeys = [data.selectedKey];
            this.selectedTreeMwyItem = data.mwyItem;
            this.selectedTreeMwqItem = data.mwqItem;
            this.selectedTreeMwpItem = data.mwpItem || '';
            this.selectedTreeTitles = this.formatTreeTitle(data.mwyItem, data.mwqItem, data.mwpItem || '');
            this.selectedTreeDateRef = data.ids;

            // 获取列表数据后滚动到展开的节点
            this.getList();

            // 滚动到展开的节点
            this.scrollToTreeNode();
          };

          const useDefaultData = () => {
            const rootNode = this.treeData[0];
            // this.expandedKeys = [rootNode.key];

            if (rootNode.children?.length > 0) {
              const firstChild = rootNode.children[0];
              // this.selectedKeys = [firstChild.key];
              // this.selectedTreeMwyItem = rootNode.data.mwsxy;
              // this.selectedTreeMwqItem = firstChild.data.mwsxq;
              this.selectedTreeTitles = '墓地区域';
              this.selectedTreeDateRef = rootNode;
              this.legendInfoBoxVisible = true;
              // this.getList();
            } else {
              // this.selectedKeys = [rootNode.key];
              // this.selectedTreeMwyItem = rootNode.data.mwsxy;
              // this.selectedTreeMwqItem = '';
              this.resultTreeData = [];
              this.legendInfoBoxVisible = true;
            }
          };

          config ? useConfigData(config) : useDefaultData();
        }
      }
    });
  }

  // 新增查找节点的方法
  findNodeByDataId(nodes: any[], targetId: string) {
    for (const node of nodes) {
      if (node?.id === targetId) {
        return node;
      }
      console.log('🚀 ~ findNodeByDataId ~ node:', node);
      console.log('🚀 ~ findNodeByDataId ~ targetId:', targetId);
      if (node.children) {
        const found = this.findNodeByDataId(node.children, targetId);
        if (found) return found;
      }
    }
    return null;
  }

  // 修改处理配置数据的方法
  handleConfigData(configData: any[]) {
    try {
      const configRes = typeof configData === 'string' ? JSON.parse(configData) : configData;
      if (!Array.isArray(configRes) || !configRes.length) return null;

      // 获取配置中的 ids
      const ids = configRes[0].ids || {};
      console.log('🚀 ~ handleConfigData ~ ids:', ids);

      // 查找园区节点
      const mwyNode = this.findNodeByDataId(this.treeData, ids.mwy);
      if (!mwyNode) return null;

      // 如果有区域ID，需要获取区域数据
      if (ids.mwq) {
        // 先获取区域数据
        return new Promise((resolve) => {
          // 设置查询参数为区域ID
          this.treeParams.view.parentRef = ids.mwq;

          Api.getList(this.treeParams).then((qResult) => {
            if (qResult.errcode === 0 && qResult.data.content.length) {
              // 找到对应的区域节点
              let qNode = this.findNodeByDataId(mwyNode.children || [], ids.mwq);
              if (!qNode) {
                // 如果找不到区域节点，创建一个新的
                const qData = qResult.data.content[0];
                qNode = {
                  id: qData.data.id,
                  title: qData.data.mwsxq,
                  value: `${qData.data.mwsxq}-${qData.data.id}`,
                  key: `${qData.data.mwsxq}-${qData.data.id}`,
                  data: qData,
                  children: [],
                };
                if (!mwyNode.children) mwyNode.children = [];
                mwyNode.children.push(qNode);
              }

              // 如果有排ID，需要继续获取排数据
              if (ids.mwp) {
                // 设置查询参数为区域ID来获取排数据
                this.treeParams.view.parentRef = ids.mwq;

                Api.getList(this.treeParams).then((pResult) => {
                  if (pResult.errcode === 0 && pResult.data.content.length) {
                    // 处理排数据
                    const arrangeData = this.processArrangeData(pResult.data.content);

                    // 更新区域节点的子节点数据
                    if (!qNode.children) qNode.children = [];

                    // 合并新的排数据，避免重复
                    const existingKeys = new Set(qNode.children.map((child) => child.key));
                    arrangeData.forEach((newNode) => {
                      if (!existingKeys.has(newNode.key)) {
                        qNode.children.push(newNode);
                      }
                    });

                    // 找到对应的排节点
                    const pNode = qNode.children.find((child) => child.data.data.id === ids.mwp);

                    // 返回完整的配置数据，包含展开的节点键值
                    resolve({
                      expandedKeys: [mwyNode.key, qNode.key], // 同时展开园区和区域节点
                      selectedKey: pNode ? pNode.key : qNode.key,
                      mwyItem: mwyNode.data.mwsxy,
                      mwqItem: qNode.data.mwsxq,
                      mwpItem: pNode ? pNode.title : '',
                      ids: {
                        mwy: ids.mwy,
                        mwq: ids.mwq,
                        mwp: ids.mwp,
                      },
                    });
                  } else {
                    // 如果获取排数据失败，返回区域级别的配置
                    resolve({
                      expandedKeys: [mwyNode.key], // 只展开园区节点
                      selectedKey: qNode.key,
                      mwyItem: mwyNode.data.mwsxy,
                      mwqItem: qNode.data.mwsxq,
                      ids: {
                        mwy: ids.mwy,
                        mwq: ids.mwq,
                      },
                    });
                  }
                });
              } else {
                // 只有区域数据时的返回
                resolve({
                  expandedKeys: [mwyNode.key], // 只展开园区节点
                  selectedKey: qNode.key,
                  mwyItem: mwyNode.data.mwsxy,
                  mwqItem: qNode.data.mwsxq,
                  ids: {
                    mwy: ids.mwy,
                    mwq: ids.mwq,
                  },
                });
              }
            } else {
              // 如果获取区域数据失败，返回园区级别的配置
              resolve({
                expandedKeys: [mwyNode.key],
                selectedKey: mwyNode.key,
                mwyItem: mwyNode.data.mwsxy,
                ids: {
                  mwy: ids.mwy,
                },
              });
            }
          });
        });
      }

      // 只有园区数据时的返回
      return {
        expandedKeys: [mwyNode.key],
        selectedKey: mwyNode.key,
        mwyItem: mwyNode.data.mwsxy,
        ids: {
          mwy: ids.mwy,
        },
      };
    } catch (error) {
      console.error('处理配置数据失败:', error);
      return null;
    }
  }

  // 修改构造树数据的方法
  constructTreeData(data, isAll = true, titleKey = 'mwsxq') {
    const mapChildren = (children, parentLabel = '') => {
      if (!children) return [];
      const uniqueValues = new Set();
      return children.reduce((acc, child) => {
        // ���用传入的 titleKey 获取显示文本
        const value = child.data[titleKey];
        const label = `${parentLabel}/${value}`;
        if (!uniqueValues.has(value)) {
          uniqueValues.add(value);
          acc.push({
            id: child.data.id,
            title: value,
            value: `${value}-${child.data.id}`,
            label,
            key: `${value}-${child.data.id}`,
            ...child,
          });
        }
        return acc;
      }, []);
    };

    const mapDataToTree = (item) => {
      const uniqueValues = new Set();
      // 根据不同级使用不同的 titleKey
      const value = item.data.mwsxy;
      const label = value;
      const children = mapChildren(item.data.t__children_, label);
      if (!uniqueValues.has(value)) {
        uniqueValues.add(value);
        return {
          id: item.data.id,
          title: value,
          value: `${value}-${item.data.id}`,
          label,
          key: `${value}-${item.data.id}`,
          children,
          ...item,
        };
      }
      return null;
    };

    const treeData = data.map(mapDataToTree).filter(Boolean);

    // 直接返回处理后的数据，不再包装成顶层节点
    return treeData;
  }

  findDataById(nodes: any[], targetId: string) {
    for (const node of nodes) {
      if (node.data?.id === targetId) {
        return node;
      }
      if (node.children) {
        const found = this.findDataById(node.children, targetId);
        if (found) return found;
      }
    }
    return null;
  }

  /**
   * 获取表数据
   * 调用Api.getList接口，传入当前组件的参数来获取列表数据
   * 此函数说明了组件如何从后端获取数据以展���列表
   */
  getList() {
    this.spinning = true;
    this.queryParams.queryCondition = [];
    const treeParams = [];
    const filters = [
      { item: this.selectedTreeMwyItem, code: 'mwy', filterType: 'Eq', propertyType: 14 },
      { item: this.selectedTreeMwqItem, code: 'mwq', filterType: 'Eq', propertyType: 14 },
      { item: this.selectedTreeMwpItem, code: 'mwp', filterType: 'Eq', propertyType: 14 },
      { item: this.selectedGraveStatus, code: 'mwzt', filterType: 'Eq', propertyType: 14 },
      { item: this.selectedShapeStatus, code: 'mx', filterType: 'Eq', propertyType: 14 },
      { item: this.searchForm['szxx.szxm'], code: 'szxx.szxm', filterType: 'Like', propertyType: 0 },
      { item: this.searchForm.xm, code: 'xm', filterType: 'Like', propertyType: 0 },
      // { item: this.searchForm.mwzt, code: 'mwzt', filterType: 'Like', propertyType: 14, propertyValue: this.getMwztPropertyValue(this.searchForm.mwzt) },
      { item: this.searchForm.mx, code: 'mx', filterType: 'Eq', propertyType: 14, propertyValue: this.getMxPropertyValue(this.searchForm.mx) },
      { item: this.compareInfo, code: 'gs', filterType: 'Eq', propertyType: 60, propertyValue: this.getCompareInfoPropertyValue(this.compareInfo) },
    ];

    if (this.searchForm.mwzt && this.searchForm.mwzt.length) {
      filters.push({ item: this.searchForm.mwzt, code: 'mwzt', filterType: 'Like', propertyType: 14, propertyValue: this.getMwztPropertyValue(this.searchForm.mwzt) });
    } else {
      if (this.filterConfig?.status?.length) {
        const statusValues = this.filterConfig.status.map((i) => i.value);
        filters.push({ item: statusValues, code: 'mwzt', filterType: 'Like', propertyType: 14, propertyValue: this.getMwztPropertyValue(statusValues) });
      }
    }

    // 遍历过滤条件，将符合条件的条件添加到 treeParams 中
    filters.forEach((filter) => {
      if (filter.item) {
        treeParams.push({
          queryFilterType: filter.filterType,
          propertyCode: filter.code,
          propertyType: filter.propertyType,
          propertyValue: filter.propertyValue || filter.item,
        });
      }
    });

    // 如果 treeParams 有值，则将 queryCondition 设置为 treeParams
    if (treeParams.length > 0) this.queryParams.queryCondition = [[[...treeParams]]];

    // 调用Api.getList接口，传入当前组件的参数来获取列表数据
    Api.getList(this.queryParams).then((result) => {
      this.spinning = false;
      if (result.errcode == 0) {
        const newList = result.data.content.map((item) => {
          item.mwy = item.data.mwy;
          item.mwq = item.data.mwq;
          item.mwp = item.data.mwp;
          item.mwh = item.data.mwh;
          return item;
        });
        const treeData = this.buildTreeStructure(newList, 'mwp', ['mwh'], 'mwp');
        console.log('🚀 ~ getList ~ treeData:', treeData);
        this.activeKey = [];
        treeData.map((item, index) => {
          this.activeKey.push(String(index + 1));
        });
        this.resultTreeData = this.sortTree(treeData, 'mwh');
        console.log('🚀 ~ getList ~ this.resultTreeData:', this.resultTreeData);
        this.isEmptyBoxVisible = !result.data.content.length;

        if (this.callbackConfig?.length) {
          const configRes = typeof this.callbackConfig === 'string' ? JSON.parse(this.callbackConfig) : this.callbackConfig;
          if (!Array.isArray(configRes) || !configRes.length) return null;

          const matchedNode = this.findDataById(this.resultTreeData, configRes[0].data.id);
          console.log('🚀 ~ getList ~ matchedNode:', matchedNode);
          if (matchedNode) {
            this.selectedItems = [matchedNode];
            // 添加延时确保 DOM 已更新
            this.$nextTick(() => {
              this.scrollToSelectedItem(matchedNode);
            });
          }
        }
      } else {
        Modal.warning({
          title: '提示',
          content: '未找到匹配的墓位信息',
        });
      }
    });
  }

  getMwztPropertyValue(item) {
    console.log('🚀 ~ getMwztPropertyValue ~ item:', item);
    if (!item) return '';
    const result = item.map((i) => {
      const name = this.tombLocationStatus.find((status) => status.value === i)?.text;
      return {
        key: i,
        value: name,
      };
    });
    console.log('🚀 ~ getMwztPropertyValue ~ result:', result);
    return JSON.stringify(result);
  }

  getMxPropertyValue(item) {
    const name = this.TombTypeLegends.find((i) => i.path == item)?.text;
    return `[{\"key\":\"${item}\",\"value\":\"${name}\"}]`;
  }

  /**
   * 处理刷新事件
   * 重置展开的节点键、选中的节点键值、墓位状态和形状状态，并重新获取树列表
   */
  handleToRefresh() {
    this.expandedKeys = ['0-0'];
    this.selectedKeys = ['0-0-0'];
    this.selectedGraveStatus = '';
    this.selectedShapeStatus = '';
    this.treeData = [];
    this.getTreeList();
  }

  /**
   * 处理树节点选事件
   * 更新选中的节点键值，并根据选中的节点获取列表
   * @param {Array} selectedKeys - 选中的节点键值数组
   * @param {Object} info - 选中的节点信息
   */
  handleOnTreeSelect(selectedKeys, info) {
    console.log('🚀 ~ handleOnTreeSelect ~ selectedKeys:', selectedKeys);
    console.log('🚀 ~ handleOnTreeSelect ~ info:', info);
    this.legendInfoBoxVisible = false;
    this.selectedKeys = selectedKeys;
    this.selectedTreeMwyItem = '';
    this.selectedTreeMwqItem = '';
    this.selectedTreeMwpItem = '';
    this.selectedTreeTitles = '';
    this.selectedTreeDateRef = {};

    // 检查是否有 filterConfig 并设置默认墓位状态
    // if (this.filterConfig?.status?.length) {
    //   // 直接使用第一个状态的 value
    //   this.searchForm.mwzt = this.filterConfig.status.map((i) => i.value);

    //   // 如果是园区级别,不设置状态
    //   // if (!info.node.dataRef.data?.mwsxq) {
    //   //   this.searchForm.mwzt = undefined;
    //   // }
    // }

    // if (info.selected) {
    // 检查是否是区级节点
    if (info.node.dataRef.data?.mwsxq) {
      console.log('区级节点:', info.node.dataRef.data?.mwsxq);
      this.selectedTreeMwyItem = info.node.dataRef.data?.mwsxy;
      this.selectedTreeMwqItem = info.node.dataRef.data?.mwsxq;
      this.selectedTreeTitles = this.formatTreeTitle(this.selectedTreeMwyItem, this.selectedTreeMwqItem, '');

      // 设置区级引用
      this.selectedTreeDateRef = {
        mwy: info.node.$parent.dataRef.data.id, // 父节点(园)的ID
        mwq: info.node.dataRef.data.id, // 当前区的ID
      };

      // 获取该区下的排数据
      this.getArrangeData(info.node.dataRef.id, info.node);
      this.getList();
    } else if (info.node.dataRef.data?.data?.mwsxp) {
      console.log('排级节点:', info.node.dataRef.data?.data?.mwsxp);
      this.selectedTreeMwyItem = info.node.dataRef.data?.data?.mwsxy;
      this.selectedTreeMwqItem = info.node.dataRef.data?.data?.mwsxq;
      this.selectedTreeMwpItem = info.node.dataRef.data?.data?.mwsxp;
      this.selectedTreeTitles = this.formatTreeTitle(this.selectedTreeMwyItem, this.selectedTreeMwqItem, this.selectedTreeMwpItem);

      // 设置排级引用
      this.selectedTreeDateRef = {
        mwy: info.node.$parent.$parent.dataRef.data.id, // 祖父节点(园)的ID
        mwq: info.node.$parent.dataRef.data.id, // 父节点(区)的ID
        mwp: info.node.dataRef.data.data.id, // 当前排的ID
      };

      this.getList();
    } else if (info.node.value === 'all' || info.node.dataRef.data?.mwsxy) {
      console.log('园级节点:', info.node.dataRef.data?.mwsxy);
      this.selectedTreeTitles = info.node.dataRef.data?.mwsxy;
      this.selectedTreeMwyItem = info.node.dataRef.data?.mwsxy;
      this.legendInfoBoxVisible = true;
      this.resultTreeData = [];

      // 设置园级引用
      this.selectedTreeDateRef = {
        mwy: info.node.dataRef.data.id,
      };
    }

    console.log('selectedTreeDateRef 更新为:', this.selectedTreeDateRef);
    // }

    // 在设置完展开节点后添加滚动
    this.$nextTick(() => {
      this.scrollToTreeNode();
    });
  }

  /**
   * 格式化树形标题
   * @param {string} mwy - 墓位园
   * @param {string} mwq - 墓位区
   * @param {string} mwp - 墓位排
   * @returns {string} 格式化后的标题
   */
  formatTreeTitle(mwy: string, mwq: string, mwp: string): string {
    const parts = [];
    if (mwy) parts.push(mwy);
    if (mwq) parts.push(mwq.includes('区') ? mwq : `${mwq}区`);
    if (mwp) parts.push(mwp.includes('排') ? mwp : `${mwp}排`);
    return parts.join(' - ');
  }

  get mwztSelectStyle() {
    return {
      width: this.getMwztWidth(),
      transition: 'width 0.3s ease-in-out',
    };
  }

  getMwztWidth() {
    const length = this.searchForm.mwzt ? this.searchForm.mwzt.length : 1;

    // 设置下拉菜单宽度,最大不超过360px
    const dropdownWidth = Math.min(Math.max(length * 240, 240), 360);
    document.documentElement.style.setProperty('--ant-select-ul-dropdown-width', dropdownWidth + 'px');
    document.documentElement.style.setProperty('--ant-select-ul-dropdown-max-width', '360px');

    const maxWidth = 360;
    // 每个选项的基础宽度为80px
    const baseWidth = Math.max(length * 90, 120);
    // 返回计算后的宽度，不超过最大宽度
    return Math.min(baseWidth, maxWidth) + 'px';
  }

  // 获取排的数据
  getArrangeData(parentId, parentNode) {
    // 修改查询参数
    this.treeParams.view.parentRef = parentId;

    Api.getList(this.treeParams).then((result) => {
      if (result.errcode == 0 && result.data.content.length) {
        // 处理排数据
        const arrangeData = this.processArrangeData(result.data.content);
        if (arrangeData && arrangeData.length > 0) {
          // 更新节点的子节点数据
          // if (!parentNode.dataRef.children) {
          parentNode.dataRef.children = [];
          // }
          // 合并新的排数据，避免重复
          const existingKeys = new Set(parentNode.dataRef.children.map((child) => child.key));
          arrangeData.forEach((newNode) => {
            if (!existingKeys.has(newNode.key)) {
              parentNode.dataRef.children.push(newNode);
            }
          });

          // 确保当前节点的 key 在 expandedKeys 中
          const nodeKey = parentNode.key || parentNode.value;
          if (nodeKey && !this.expandedKeys.includes(nodeKey)) {
            this.expandedKeys = [...this.expandedKeys, nodeKey];
          }

          // 同时展开父节点
          const parentKey = parentNode.$parent?.key || parentNode.$parent?.value;
          if (parentKey && !this.expandedKeys.includes(parentKey)) {
            this.expandedKeys = [...this.expandedKeys, parentKey];
          }

          // 更新树数据��触发重新渲染
          this.treeData = [...this.treeData];
        }
      }
    });
  }

  // 修改处理排数据的方法
  processArrangeData(data) {
    // 按排号分组
    const groups = data.reduce((acc, item) => {
      const p = item.data.mwsxp;
      if (!acc[p]) {
        acc[p] = [];
      }
      acc[p].push(item);
      return acc;
    }, {});

    // 转换为树节点格式
    return Object.entries(groups)
      .map(([p, items]) => {
        // 检查是否已包含"排"字
        const title = p;
        return {
          id: items[0].id,
          title: title,
          value: `${p}-${items[0].id}`,
          key: `${p}-${items[0].id}`,
          label: title,
          children: [], // 暂不处�����墓���数据
          data: items[0],
        };
      })
      .sort((a, b) => {
        // 提取数字部分,支持中英文混合字符
        const aMatch = a.title.match(/[0-9]+|[一二三四五六七八九十百千万亿]+/);
        const bMatch = b.title.match(/[0-9]+|[一二三四五六七八九十百千万亿]+/);

        if (!aMatch || !bMatch) {
          // 如果没有数字,按原字符串比较
          return a.title.localeCompare(b.title);
        }

        const aNum = this.parseChineseNumber(aMatch[0]);
        const bNum = this.parseChineseNumber(bMatch[0]);

        return aNum - bNum;
      });
  }

  // 新增:解析中文数字
  parseChineseNumber(str: string): number {
    // 如果是阿拉伯数字直接返回
    if (/^\d+$/.test(str)) {
      return parseInt(str);
    }

    const chineseNumbers = {
      一: 1,
      二: 2,
      三: 3,
      四: 4,
      五: 5,
      六: 6,
      七: 7,
      八: 8,
      九: 9,
      十: 10,
      百: 100,
      千: 1000,
      万: 10000,
      亿: 100000000,
    };

    let result = 0;
    let temp = 0;
    let prev = 0;

    for (let i = 0; i < str.length; i++) {
      const curr = chineseNumbers[str[i]];

      if (curr >= 10) {
        // 是单位
        if (temp) {
          result += temp * curr;
        } else {
          result += curr;
        }
        temp = 0;
      } else {
        // 是数字
        temp = curr;
        if (i === str.length - 1) {
          result += temp;
        }
      }
      prev = curr;
    }

    return result || parseInt(str);
  }

  /**
   * 处理树展开事件
   * 更新展开的节点键值
   * @param {Array} expandedKeys - 展开的节点键值数组
   */
  handleOnTreeExpand(expandedKeys, info) {
    this.expandedKeys = expandedKeys;
    // this.selectedTreeNode = info.node;
  }

  /**
   * 处理项目点击事件
   * 获取项目详情并显示模框
   * @param {Object} item - 点击的项目对象
   */
  handleItemClick(item) {
    if (!item.data.id) {
      return Modal.warning({
        title: '提示',
        content: '数据获取异常，刷新重新刷取',
        onOk() {
          location.reload();
        },
      });
    }
    const loading = this.$message.loading('数据加载中...');
    this.detailParams.objectId = item.data.id;
    Api.getDetail(this.detailParams).then(({ errcode, data }) => {
      loading();
      if (errcode == 0) {
        this.modalItem = data.bizObject;
        this.detailModalTitle = `${item.data.name}`;
        this.detailVisible = true;
        this.handleSelectTombItem(item);

        // 添加延时确保 DOM 已更新
        this.$nextTick(() => {
          // 如果不是复制状态才滚动到选中项
          if (this.callbackConfig) {
            this.scrollToSelectedItem(item);
          }
        });
      } else {
        Modal.warning({
          title: '提示',
          content: '数据获取异常，刷新重新刷取',
        });
      }
    });
  }

  handleSelectTombItem(item: any) {
    console.log('item', item);
    console.log('this.selectedTreeDateRef', this.selectedTreeDateRef);
    // 将完整的引用对象传递给 item
    item.ids = this.selectedTreeDateRef;

    if (this.multiple) {
      const index = this.selectedItems.findIndex((i) => i.data.id === item.data.id);
      if (index > -1) {
        this.selectedItems.splice(index, 1);
      } else {
        this.selectedItems.push(item);
      }
    } else {
      this.selectedItems = [item];
    }

    if (this.onSelect) {
      this.onSelect(this.selectedItems);
    }
  }

  /**
   * 处理详情弹窗取消事件
   */
  handleDetailCancel() {
    this.detailVisible = false;
  }

  /**
   * 处理取消事件
   * 将模态框的可见性设置为 false
   */
  handleCancel() {
    this.visible = false;
  }

  /**
   * 处理菜单点击事件
   * 根据点击的菜项更新墓位状态或形状状态，并重新获取列表
   * @param {Object} e - 击事件对象
   * @param {String} type - 类型（'status' 或其他）
   */
  handleMenuClick(e, type) {
    if (type == 'status') {
      this.selectedGraveStatus = this.tombLocationStatus[e.key].text;
    } else {
      this.selectedShapeStatus = this.TombTypeLegends[e.key].text;
    }
    this.getList();
  }

  handleEditPriceTreeChange(value) {
    console.log('🚀 ~ handleEditPriceTreeChange ~ value:', value);
    if (!value) {
      this.phTreeData = [];
      this.editPriceForm.mwp = '';
      this.editPriceForm.mwh = '';
      this.editPriceForm.mwy = '';
      this.editPriceForm.mwq = '';
    }
  }

  handlePHTreeChange(value) {
    if (!value) {
      this.editPriceForm.mwp = '';
      this.editPriceForm.mwh = '';
    }
  }

  /**
   * 处理编辑价格按钮点击事件
   * 将编辑价格模态框的可见性设置为 true
   */
  handleToEditPrice() {
    // 清空editPriceForm的值
    this.editPriceForm = {
      all: undefined,
      mwjg: '',
      glf: '',
      mwy: '',
      mwq: '',
      mwp: '',
      mwh: '',
      mwzt: undefined,
    };
    this.editPriceVisible = true;
  }

  /**
   * 将键值映射到标题
   * @param {Array} keys - 键值数组
   * @param {Array} nodes - 节点数组
   * @returns {Array} - 标题数组
   */
  mapKeysToTitles(keys, nodes) {
    const titles = [];
    nodes.forEach((node) => {
      if (keys.includes(node.value)) {
        titles.push(node.title);
      }
      if (node.children) {
        titles.push(...this.mapKeysToTitles(keys, node.children));
      }
    });
    return titles;
  }

  /**
   * 处理编辑价格树选择事件
   * @param {Array} value - 选中的值
   * @param {Object} node - 选中的节点
   * @param {Object} info - 选择信息
   */
  handleEditPriceTreeSelect(value, node, info) {
    console.log('🚀 ~ handleEditPriceTreeSelect ~ value:', value);
    console.log('🚀 ~ handleEditPriceTreeSelect ~ node:', node);
    console.log('���� ~ handleEditPriceTreeSelect ~ info:', info);
    if (info.selected) {
      // const titles = this.mapKeysToTitles(value, this.copyTreeData);
      const titles = [];
      let currentNode = node;
      while (currentNode && currentNode.title) {
        titles.unshift(currentNode.title);
        currentNode = currentNode.$parent;
      }
      console.log('🚀 ~ handleEditPriceTreeSelect ~ titles:', titles);
      if (titles.length > 0) {
        const [mwy, mwq] = titles;
        this.editPriceForm.mwy = mwy || '';
        this.editPriceForm.mwq = mwq || '';
        this.phTreeData = [];
        if (mwq) this.getPHList(mwy, mwq);
      }

      console.log('🚀 ~ handleEditPriceTreeSelect ~ this.editPriceForm:', this.editPriceForm);
    }
  }

  /**
   * 获取列表数据
   * 调用Api.getList接口，传入当前组件的参数来获取列表数据
   * 此函数说明了组件如何从后端取数据以展示列表
   */
  getPHList(mwy, mwq) {
    this.phSpinning = true;
    this.queryParams.queryCondition = [];
    const treeParams = [];
    const filters = [
      { item: mwy, code: 'mwy' },
      {
        item: mwq,
        code: 'mwq',
      },
    ];

    // 遍历过滤条件，将符合条件的条件添加到 treeParams 中
    filters.forEach((filter) => {
      if (filter.item) {
        treeParams.push({
          queryFilterType: 'Eq',
          propertyCode: filter.code,
          propertyType: 14,
          propertyValue: filter.item,
        });
      }
    });

    // 如果 treeParams 有值，则将 queryCondition 设置为 treeParams
    if (treeParams.length > 0) this.queryParams.queryCondition = [[[...treeParams]]];

    // 调用Api.getList接口，传入当前组件的参数来获取列表数据
    Api.getList(this.queryParams).then((result) => {
      this.phSpinning = false;
      if (result.errcode == 0) {
        const newList = result.data.content.map((item) => {
          item.mwy = item.data.mwy;
          item.mwq = item.data.mwq;
          item.mwp = item.data.mwp;
          item.mwh = item.data.mwh;
          return item;
        });
        let treeData = this.buildTreeStructure(newList, 'mwp', ['mwh'], 'mwp');
        treeData = this.sortTree(treeData, 'mwh');
        this.phTreeData = treeData;
        console.log('🚀 ~ getPHList ~ this.phTreeData:', this.phTreeData);
      } else {
        Modal.warning({
          title: '提示',
          content: '数据获取异常，刷新重新刷取',
        });
      }
    });
  }

  handlePHTreeSelect(value, node, info) {
    console.log('🚀 ~ handleEditPriceTreeSelect ~ value:', value);
    console.log('🚀 ~ handleEditPriceTreeSelect ~ node:', node);
    console.log('🚀 ~ handleEditPriceTreeSelect ~ info:', info);
    if (info.selected) {
      const titles = [];
      let currentNode = node;
      while (currentNode && currentNode.title) {
        titles.unshift(currentNode.title);
        currentNode = currentNode.$parent;
      }
      console.log(' ~ handleEditPriceTreeSelect ~ titles:', titles);
      if (titles.length > 0) {
        const [mwp, mwh] = titles;
        this.editPriceForm.mwp = mwp || '';
        this.editPriceForm.mwh = mwh || '';
      }
      console.log('🚀 ~ handleEditPriceTreeSelect ~ this.editPriceForm:', this.editPriceForm);
    }
  }

  /**
   * 处理编辑价格确认事件
   * 验证表单并提交更新请求
   */
  handleEditPriceOk() {
    const formRef = this.$refs.editPriceFormRef as any;
    formRef.validate();
    console.log('🚀 ~ handleEditPriceOk ~ this.editPriceForm:', this.editPriceForm);

    // 检查墓位价格和管理费是否至少填写一个
    if (!this.editPriceForm.mwjg && !this.editPriceForm.glf) {
      Modal.warning({
        title: '提示',
        content: '墓位价格和管理费必须至填写一个',
      });
      return;
    }
    // 调用API更新位价格
    Api.updateTombLocationPrices(this.editPriceForm).then((result) => {
      console.log('🚀 ~ handleEditPriceOk ~ result:', result);
      if (result.errcode == 0) {
        if (result.data > 0) {
          this.$message.success('更新成功');
          this.editPriceVisible = false;
        } else this.$message.error('未查询到相关数据更新');
      } else {
        this.$message.error('更新失败');
      }
    });
  }

  /**
   * 根据墓型设置墓位数量，并填充默认数据
   * @param {Object} data - 墓位数据
   * @returns {Array} - 填后的墓位数据数组
   */
  setCounts(data) {
    let count = 1;
    switch (data.mx) {
      case '多穴墓型':
        count = 4;
        break;
      case '双穴墓型':
        count = 2;
        break;
    }

    const newArray = new Array(count).fill({ ...data });
    const list = data.szxx || [];

    // 获取基础背景色
    const baseColor = this.setTombstoneStatusBg(data);

    // 遍历每个位置设置背景色
    return newArray.map((item, index) => {
      const isOccupied = index >= count - list.length;

      let bg = baseColor;

      // 判断是否为已安葬状态
      if (data.mwzt === '已安葬') {
        // 只有在已占用的位置才改变颜色
        if (index < list.length) {
          // 检查安葬类型
          if (data.azlxKey) {
            // 如果是 option3 或 option4，使用纯黑色
            if (['option3', 'option4'].includes(data.azlxKey)) {
              bg = '#000000';
            } else {
              // 其他安葬类型使用默认已安葬颜色
              bg = this.legendTombLocationStatus.find((item) => item.text === '已安葬')?.group?.find((g) => g.value === 'yaz')?.color;
            }
          } else if (data.szxx?.length) {
            // 如果没有安葬类型但有逝者信息，也使用纯黑色
            bg = '#000000';
          }
        }
      } else if (isOccupied && data.mwzt === '已销售') {
        // 已销售且被占用的情况
        bg = this.legendTombLocationStatus.find((item) => item.text === '已销售')?.group?.find((g) => g.value === 'yxsaz')?.color;
      }

      return {
        ...item,
        bg,
      };
    });
  }

  /**
   * 设置墓碑状态的背景颜色
   * @param {Object} data - 墓碑数据对象
   * @returns {string | undefined} - 返回对状态的颜色，如果未找到则返回 undefined
   */
  setTombstoneStatusBg(data: any) {
    if (data.mwzt) {
      // 查���与墓位状态匹配的项
      let findItem: any = this.tombLocationStatus.find((item: any) => item.text == data.mwzt);
      // 返回找到的项的��色
      return findItem?.color;
    }
  }

  /**
   * 构建树形结构
   * @param {Array} data - 数据数组
   * @param {string} rootKey - 根节点的键
   * @param {Array} childKeys - 子节点的键数组
   * @param {string} sortKey - 用于排序的键
   * @returns {Array} - 树形结构数
   */
  buildTreeStructure(data, rootKey, childKeys, sortKey) {
    const tree = {};

    let uniqueKeyCounter = 0; // 用于生成唯一键值的计数器

    /**
     * 生成唯一键值
     * @param {string} parentKey - 父节点的键
     * @param {number} index - 当前引
     * @returns {string} - 唯一键值
     */
    function generateUniqueKey(parentKey, index) {
      return parentKey ? `${parentKey}-${index + 1}` : `0-${index}`;
    }

    data.forEach((item) => {
      const rootValue = item[rootKey];

      // 如根节点还没有出现在树中，创建一个新的子树
      if (!tree[rootValue]) {
        const key = generateUniqueKey(null, Object.keys(tree).length);
        tree[rootValue] = {
          title: rootValue,
          children: [],
          value: key,
          key,
          label: rootValue, // 始化label为根节值
        };
      }

      // 获取根节点
      let currentNode = tree[rootValue];

      // 构建子节点层级
      childKeys.forEach((key) => {
        const value = item[key];
        let foundChild = false;
        currentNode.children.forEach((child) => {
          if (child.title === value) {
            currentNode = child;
            foundChild = true;
            return true;
          }
        });

        if (!foundChild) {
          const key = generateUniqueKey(currentNode.key, currentNode.children.length);
          const newChild = {
            title: value,
            children: [],
            key,
            value: key,
            label: `${currentNode.label}/${value}`, // 更新label为全路径
          };
          currentNode.children.push(newChild);
          currentNode = newChild;
        }
      });
      // 添加整个数据对象作为属性
      if (childKeys.length > 0) {
        currentNode.data = item;
        // 根据状态设置背景颜色
        currentNode.data.bg = this.setTombstoneStatusBg(item.data);
      }
    });

    // 转换树为数组形式
    const treeArray = Object.values(tree).map((rootNode: any) => {
      // 确保 children 是一个对象数组，否则回 undefined
      const children = rootNode.children.length > 0 ? rootNode.children : undefined;
      return {
        ...rootNode,
        children,
      };
    });

    if (!sortKey) return treeArray;

    // 对树进行排序

    // 检查是否存在多个顶层树形结构
    const hasMultipleRoots = treeArray.length > 1;

    // 对顶层树形结构进��排序（如果有多个的话）
    const sortedTreeArray = hasMultipleRoots ? this.sortTree(treeArray, sortKey) : treeArray;

    // 无论顶层树形结构数��如何，都需要对个顶层结构的子节点进行排序
    sortedTreeArray.forEach((rootNode) => {
      if (rootNode.children && rootNode.children.length > 1) {
        rootNode.children = this.sortTree(rootNode.children, sortKey);
      }
    });
    return sortedTreeArray;
  }

  /**
   * 对树形结构进行排序
   * @param {Array} tree - 树形结构数组
   * @param {string} sortKey - 用于排序的键
   * @returns {Array} - 排序后的树形结构数组
   */
  sortTree(tree, sortKey) {
    // 确保是数组
    if (!Array.isArray(tree)) return tree;

    // 对当前层级进行排序
    const sorted = [...tree].sort((a, b) => {
      // 获取排序值
      const aValue = sortKey && a.data ? a.data[sortKey] : a.title || '';
      const bValue = sortKey && b.data ? b.data[sortKey] : b.title || '';

      // 使用辅助方进行比较
      return this.compareValues(aValue, bValue);
    });

    // 递归处理子节点
    return sorted.map((node) => {
      if (node.children && node.children.length > 0) {
        return {
          ...node,
          children: this.sortTree(node.children, sortKey),
        };
      }
      return node;
    });
  }

  // 新增一个比较值的辅助方法
  compareValues(aValue: string, bValue: string) {
    // 提取第一个数字
    const aMatch = aValue?.match(/0*(\d+)/);
    const bMatch = bValue?.match(/0*(\d+)/);

    // 如果两个值都包数字
    if (aMatch && bMatch) {
      const aNum = parseInt(aMatch[0]);
      const bNum = parseInt(bMatch[0]);
      return aNum - bNum;
    }

    // 如果只一个包含数字将包含数字的值排在前面
    if (aMatch) return -1;
    if (bMatch) return 1;

    // 如果都不含数字，按字符串比较
    return (aValue || '').localeCompare(bValue || '');
  }

  // 处理搜索
  handleSearch() {
    // if (!this.selectedTreeMwyItem || !this.selectedTreeMwqItem) {
    //   this.$message.warning('请先选择墓位区域');
    //   return;
    // }
    console.log('🚀 ~ handleSearch ~ this.filterConfig:', this.filterConfig);
    console.log('🚀 ~ handleSearch ~ this.searchForm:', this.searchForm.mwzt);
    if (this.searchForm.mwzt && this.searchForm.mwzt.length == 0 && this.filterConfig?.status?.length > 0) {
      this.searchForm.mwzt = undefined;
    }
    // 重新获取列表数据
    this.getList();
  }

  // 重置搜索
  handleResetSearch() {
    this.searchForm = {
      'szxx.szxm': '',
      xm: '',
      // mwh: '',
      mwzt: undefined,
      mx: undefined,
    };
    if (this.filterConfig?.status?.length && this.searchForm.mwzt && this.searchForm.mwzt.length) {
      // 直接使用第一个状态的 value
      this.searchForm.mwzt = undefined;
    }
    this.handleSearch();
  }

  created() {
    // 当弹窗显示时初始化数据
    this.$watch('visible', (newVal) => {
      if (newVal) {
        this.expandedKeys = [];
        this.selectedKeys = [];
        // 初始化 tombLocationStatus
        this.initTombLocationStatus();
        this.getTreeList();
        this.getCompareInfo();
      }
    });

    // 监听 filterConfig 的变化
    this.$watch('filterConfig', () => {
      this.initTombLocationStatus();
    });
  }

  // 添加初始化 tombLocationStatus 的方法
  initTombLocationStatus() {
    const defaultStatus = [
      { text: '待售', value: 'ds', color: '#32CD32' },
      { text: '未开放', value: 'wkf', color: '#DDA0DD' }, // LimeGreen
      { text: '已预留', value: 'yyl', color: '#FF1493' },
      { text: '已预订', value: 'yyd', color: '#FF6347' },
      {
        text: '已销售',
        value: 'yxs',
        color: '#4682B4',
        group: [
          { text: '未存逝者', value: 'yxs', color: '#4682B4' },
          { text: '已存逝者', value: 'yxsaz', color: '#2F4F4F' },
        ],
      },
      { text: '已安葬', value: 'yaz', color: '#708090' },
      { text: '已迁出', value: 'yqc', color: '#DC143C' },
      { text: '二次预留', value: 'ecyl', color: '#8A2BE2' },
      { text: '二次预订', value: 'ecyd', color: '#FF8C00' },
      { text: '二次销售', value: 'ecxs', color: '#20B2AA' },
      { text: '二次销售安葬', value: 'ecxsaz', color: '#8B0000' },
    ];

    // 使用计算属性获取配置
    const config = this.processedFilterConfig;

    // 如果有 status 配置，则根据配置更新状态列表
    if (config?.status && Array.isArray(config.status)) {
      // 创建一个映射来快速查找配置的状态
      const configStatusMap = new Map(config.status.map((item) => [item.value, item]));

      // 只保留配置中指定的状态
      this.tombLocationStatus = defaultStatus
        .filter((status) => configStatusMap.has(status.value))
        .map((status) => ({
          ...status,
          ...configStatusMap.get(status.value),
        }));
    } else {
      // 如果没有配置，使用默认状态列表
      this.tombLocationStatus = [...defaultStatus];
    }

    // 同步更新 legendTombLocationStatus
    // this.legendTombLocationStatus = [
    //   ...this.tombLocationStatus,
    //   { text: '未存逝者-未安葬', value: 'yaz', color: '#708090' },
    //   { text: '已存逝者-已安葬', value: 'yaz', color: '#000000' }
    // ];
  }

  toggleCollapse() {
    this.isCollapsed = !this.isCollapsed;
  }

  formatRowNumber(title: string) {
    // 提取数字
    // const num = title?.match(/0*(\d+)/);
    // if (num) {
    //   // 将数字转换为大写中文
    //   const chineseNum = this.numberToChinese(parseInt(num[0]));
    //   // 如果标题已经包含"排"字，则不添加
    //   return title.includes('排') ? `${chineseNum}\n排` : `${chineseNum}\n排`;
    // }
    return title;
  }

  // 数字转中文大写方法
  numberToChinese(num: number): string {
    const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
    if (num <= 10) {
      return chineseNums[num];
    } else if (num < 20) {
      return '十' + (num % 10 === 0 ? '' : chineseNums[num % 10]);
    } else {
      return chineseNums[Math.floor(num / 10)] + '十' + (num % 10 === 0 ? '' : chineseNums[num % 10]);
    }
  }

  toggleStatsCollapse() {
    this.isStatsCollapsed = !this.isStatsCollapsed;
  }

  // 修改显判断方法
  shouldShowName(data: any): boolean {
    // 检查是否需要显示逝者姓名
    if (this.searchForm['szxx.szxm'] && data.szxx && data.szxx.length) {
      return true;
    }
    // 检查否需要显示家属姓名
    if (this.searchForm.xm && data.xm) {
      return true;
    }
    return false;
  }

  // 修改关闭方法
  handleClose() {
    // 如果有回调函数，先执行回调
    if (typeof this.onClose === 'function') {
      this.onClose();
    }
    // 调用全局方法关闭弹窗
    window.$modalMwksh.hide();
  }

  // 修改确认方法
  handleDetailConfirm() {
    if (this.selectedItems.length === 0) {
      this.$message.warning('请先选择墓位');
      return;
    }

    // 如果有确认回调，执行回调并传入选中的墓位信息
    if (typeof this.onConfirm === 'function') {
      this.onConfirm(this.selectedItems);
    }
    this.handleDetailCancel();

    // 调用全局方法关闭弹窗
    window.$modalMwksh.hide();
  }

  // 判断是否应该显示墓穴名称
  shouldShowTombName(mitem: any, index: number, data: any): boolean {
    if (!this.searchForm['szxx.szxm'] && !this.searchForm.xm) {
      return false;
    }

    // 如果���搜索逝者姓名
    if (this.searchForm['szxx.szxm'] && data.szxx && data.szxx[index]) {
      return true;
    }

    // 如果是搜索家属姓名
    if (this.searchForm.xm && data.xm && index === data.szxx.length - 1) {
      return true;
    }

    return false;
  }

  // 获取要显示的名称
  getTombName(mitem: any, index: number, data: any): string {
    if (this.searchForm['szxx.szxm'] && data.szxx && data.szxx[index]) {
      return data.szxx[index].szxm;
    }
    if (this.searchForm.xm && data.xm) {
      return data.xm;
    }
    return '';
  }

  /**
   * 获取状态对应的颜色
   */
  getStatusColor(status: string): string {
    const statusMap = {
      待售: 'green',
      已预留: 'gold',
      已预订: 'orange',
      已销售: 'blue',
      已安葬: 'gray',
      已迁出: 'red',
    };
    return statusMap[status] || 'default';
  }

  /**
   * 格式化逝者姓名显示
   * @param szxx 逝者信息数组
   * @param truncate 是否截断显示
   * @returns 格式化后的姓名字符串
   */
  formatDeceasedNames(szxx: any[], truncate: boolean = false): string {
    if (!szxx || !szxx.length) return '';

    // 过滤掉无效的姓名
    const validNames = szxx.map((item) => item.szxm).filter(Boolean);

    if (validNames.length === 0) return '';
    if (validNames.length === 1) return validNames[0];

    // 如果需要截断显示且人数大于1
    if (truncate && validNames.length > 1) {
      return `${validNames[0]}等${validNames.length}人`;
    }

    // 完整显示所有姓名
    return validNames.join('、');
  }

  // 在 mounted 中添加全屏变化监听
  mounted() {}

  beforeDestroy() {}

  // 新增滚动到选中项的方法
  scrollToSelectedItem(item: any) {
    try {
      // 获取列表容器
      const listSection = document.querySelector('.list-section');
      if (!listSection) return;

      // 获取选中的墓位元素
      const selectedElement = document.querySelector(`.item-box.selected`);
      if (!selectedElement) return;

      // 计算滚动位置
      const containerRect = listSection.getBoundingClientRect();
      const elementRect = selectedElement.getBoundingClientRect();

      // 计算元素相对于容器的位置
      const relativeTop = elementRect.top - containerRect.top;

      // 滚动到选中项,并留出一定空间
      listSection.scrollTo({
        top: listSection.scrollTop + relativeTop - containerRect.height / 3,
        behavior: 'smooth',
      });
    } catch (error) {
      console.error('滚动到选中项失败:', error);
    }
  }

  // 修改滚动到树节点的方法
  scrollToTreeNode() {
    this.$nextTick(() => {
      try {
        // 获取树容器
        const treeContainer = this.$refs.treeRef?.$el?.querySelector('.ant-tree') || document.querySelector('.ant-tree');
        if (!treeContainer) {
          console.log('Tree container not found');
          return;
        }

        // 获取选中的节点
        const selectedKey = this.selectedKeys[0];
        if (!selectedKey) {
          console.log('No selected key found');
          return;
        }

        // 获取目标节点 - 使用 data-key 属性查找
        const targetNode = treeContainer.querySelector(`.ant-tree-treenode-selected`);
        if (!targetNode) {
          console.log('Target node not found for key:', selectedKey);
          return;
        }

        // 计算滚动位置
        const containerRect = treeContainer.getBoundingClientRect();
        const nodeRect = targetNode.getBoundingClientRect();
        const relativeTop = nodeRect.top - containerRect.top;

        console.log('Scrolling to position:', {
          currentScroll: treeContainer.scrollTop,
          relativeTop,
          targetScroll: treeContainer.scrollTop + relativeTop - containerRect.height / 3,
        });

        // 滚动到节点位置，并留出一些空间
        treeContainer.scrollTo({
          top: treeContainer.scrollTop + relativeTop - containerRect.height / 3,
          behavior: 'smooth',
        });
      } catch (error) {
        console.error('滚动到树节点失败:', error);
      }
    });
  }

  // 4. 在组件中添加计算属性来扁平化数据
  get flattenedTombData() {
    return this.resultTreeData.map((item, index) => ({
      ...item,
      id: `row-${index}`,
      size: Math.max(200, this.calculateRowHeight(item)), // 动态计算每行的高度
    }));
  }

  // 添加计算行高的方法
  calculateRowHeight(item: any): number {
    const baseHeight = 200; // 基础高度
    const itemsPerRow = Math.floor((window.innerWidth - 300) / 130); // 估算每行可容纳的墓位数
    const rowsNeeded = Math.ceil((item.children?.length || 0) / itemsPerRow); // 计算需要的行数
    return baseHeight * Math.max(1, rowsNeeded); // 返回最小200px的高度
  }

  getTombstoneComponent(mx) {
    switch (mx) {
      case '双穴墓型':
        return 'tombstone-item-2';
      case '多穴墓型':
        return 'tombstone-item-4';
      default:
        return 'tombstone-item';
    }
  }

  // 添加一个计算属性来处理 filterConfig
  get processedFilterConfig(): Record<string, any> {
    if (typeof this.filterConfig === 'string') {
      try {
        return JSON.parse(this.filterConfig);
      } catch (e) {
        console.error('Failed to parse filterConfig string:', e);
        return {};
      }
    }
    return this.filterConfig;
  }
}
</script>

<style lang="less" scoped>
@import url('./index.less');
</style>
